package com.jianganming.bio.rpc.client;

import com.jianganming.bio.rpc.request.RpcRequest;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class RpcNetTransport {
    private String host;
    private int port;

    public RpcNetTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public Object send(RpcRequest request) {
        Socket socket = null;
        Object result = null;
        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;
        try {
            socket = new Socket(host,port);
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(request);//写入输出流到服务端

            inputStream = new ObjectInputStream(socket.getInputStream());
            result = inputStream.readObject();//读取服务端返回数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(outputStream !=null){
                    outputStream.close();
                }
                if(inputStream !=null){
                    inputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return result;

    }
}
